<?php

namespace Controller\OAuth;

class QQ extends Base {

	public function actionIndex() {
		$fromUrl = $this->getParam('fromurl');
		$fromUrl = urldecode($fromUrl);
		$fromUrl = $fromUrl ? $fromUrl : '/';
		$redirect = \Lib\Util\Comm::getCurrentUrl();
		$token = $this->getToken($redirect);
		$url = 'https://graph.qq.com/oauth2.0/me?access_token=' . $token;
		$str = \Lib\Util\Comm::request($url);
		$start = strpos($str, '{');
		$end = strpos($str, '}');
		$str = substr($str, $start, $end - $start + 1);
		$result = json_decode($str, true);
		$openId = !empty($result['openid']) ? $result['openid'] : '';
		$appId = !empty($result['client_id']) ? $result['client_id'] : '';
		if (!$openId) {
			$this->throwException('获取openid失败');
		}
		$url = 'https://graph.qq.com/user/get_user_info?access_token=' . $token .'&oauth_consumer_key=' . $appId . '&openid=' . $openId;
		$userJson = \Lib\Util\Comm::request($url);
		$qqInfo = json_decode($userJson, true);
		$nickname = $qqInfo['nickname'];
		$sex = $qqInfo['gender'] == '男' ? \Data\Base::SEX_BOY : \Data\Base::SEX_GIRL;
		$photo = $qqInfo['figureurl_qq_2'];
		$authId = \Business\User::instance()->replaceQQ($openId, $nickname, $sex, $photo);
		// 通过authId获取用户Id
		$ip = $this->getIp();
		$userId = \Business\User::instance()->getUserIdByAuthId($authId, $ip);
		$userMask = $this->getUserMask();
		if ($userId) {
			\Business\User::instance()->setUserLoginMask($userMask, $userId, $ip);
			\Lib\Util\Comm::redirect($fromUrl);
		} else {
			\Business\User::instance()->setUserAuthId($userMask, $authId);
			\Lib\Util\Comm::redirect('/Passport/Bind?fromurl=' . urlencode($fromUrl));
		}
	}

	private function getToken($redirect) {
		$code = $this->getParam('code');
		$state = $this->getParam('state');

		if ($code && $state) {
			$token = $this->getRemoteToken($code, $state, $redirect);
			return $token;
		}
		$url = 'https://graph.qq.com/oauth2.0/authorize';
		$url .= '?response_type=code';
		$url .= '&client_id=' . \Config\OAuth::QQ_CLIENT_ID;
		$url .= '&redirect_uri=' . urlencode($redirect);
		$url .= '&state=hfdend';
		\Lib\Util\Comm::redirect($url);
	}

	private function getRemoteToken($code, $state, $redirect) {
		$url = 'https://graph.qq.com/oauth2.0/token';
		$url .= '?grant_type=authorization_code';
		$url .= '&client_id=' . \Config\OAuth::QQ_CLIENT_ID;
		$url .= '&client_secret=' . \Config\OAuth::QQ_CLIENT_SECRET;
		$url .= '&code=' . $code;
		$url .= '&redirect_uri=' . urlencode($redirect);
		$str = \Lib\Util\Comm::request($url);
		$v = $this->convertUrlQuery($str);
		$token = !empty($v['access_token']) ? $v['access_token'] : '';
		$expires = !empty($v['expires_in']) ? $v['expires_in'] : 0;
		if (!$token) {
			$this->throwException('获取token失败');
		}
		return $token;
	}
}